package com.xuesong.jwt;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xuesong.user.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ClassName: JwtUtil
 * @Description:
 * @author: Gong_Xuesong
 * @date 2021/12/7 16:05
 */
public class JwtUtil {
    /**
     * 过期时间为一天
     * TODO 正式上线更换为15分钟
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "gongxuesongzuishuaile";


    private static final String JWT_KEY = "token";

    private String getToken(String id) {
        //签发日期
        Date nowDate = new Date();
        //过期时间
        Date overDate = DateUtil.offsetMinute(nowDate, 15);

        return JWT.create().withSubject("gong")
                .withAudience("pc")
                .withSubject(id)
                .withIssuedAt(nowDate)
                .withExpiresAt(overDate)
                .sign(Algorithm.HMAC256(TOKEN_SECRET));

    }


    /**
     * 从header获取token
     */
    private static String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (request == null) {
            return null;
        }
        return request.getHeader(JWT_KEY);
    }

    public Long getUserId(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
        DecodedJWT verify = build.verify(token);
        String subject = verify.getSubject();
        return Long.valueOf(subject);
    }

}
